
async function workerManager(jsPath){
	let res=await fetch(jsPath);
	let jsCode=await res.text();
	/* jsCode+=`
	onmessage=async ev=>{
		let {id,name}=ev.data;
		if(name && self[name]){
			let data=await self[name]();
			//let res2=await new Blob([JSON.stringify({id,data:res})]).arrayBuffer();
			postMessage({id,data});
			data=null;
		}
	}`; */
	let blob=new Blob([jsCode],{type:"text/javascript"});
	let worker=new SharedWorker(URL.createObjectURL(blob)),id=0;
	let cachePromise={}
	worker.port.onmessage=async ev=>{
		//let msg=await new Blob([ev.data]).text();
		let msg=JSON.parse(ev.data);
		//msg=ev.data;
		//console.log(Date.now()-msg.time)
		if(cachePromise[msg.id]){
			cachePromise[msg.id].resolve(msg.data);
		}
		ev=null;
		//worker.postMessage(ev.data,[ev.data]);
	}
	function destroy(){
		worker.port.close();
		cachePromise={};
	}
	function exec(name,data){
		id++;
		worker.port.postMessage({id,name,data});
		cachePromise[id]=Promise.withResolvers();
		return cachePromise[id].promise;
	}
	//setTimeout(console.log(worker),500)
	return new Proxy({},{
		get(target,key){
			if(key=="destroy"){
				return destroy;
			}else if(key=="worker"){
				return worker;
			}else{
				if(key=='then'){
					return null;
				}
				return data=>exec(key,data);
			}
		}
	});	
}
export {workerManager};